package com.spzx.channel.configure;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author Haoran Sun
 * @since 2024/07/27
 */

@Configuration
public class ThreadPoolConfig {

    @Bean
    public ThreadPoolExecutor executor(){
        //运行环境的线程数
        int processors = Runtime.getRuntime().availableProcessors();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                processors,
                processors * 2,
                60,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(200),
                Executors.defaultThreadFactory(),
                //拒绝策略
                (runnable, executor) -> {
                    try {
                        int retryTtl =  new Random().nextInt(3);
                        TimeUnit.SECONDS.sleep(retryTtl);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    executor.submit(runnable);
                }
        );
        threadPoolExecutor.prestartAllCoreThreads();
        return threadPoolExecutor;
    }

}
